import { _decorator, Component, Label, Node, Pool, tween, Tween, v3 } from 'cc';
import { AudioManager } from '../../AudioManager';
import { Url } from '../../Url';
import GlobalData from '../../game/GlobalData';
import { LocalStorageMgr } from '../../game/LocalStorageMgr';
import { MainGameLogic } from '../../game/MainGameLogic';
import { NCPoint } from '../api/api.config.client';
import { ClientAPI } from '../api/client.api';
import ServiceAPI from '../api/service.api';
import PoolManager from '../../PoolManager';
const { ccclass, property } = _decorator;

@ccclass('LuckywardPageNew')
export class LuckywardPageNew extends Component {
    public pageConfig: any = null;

    @property(Label)
    maxWardLabel: Label = null;
    @property(Label)
    lessWardLabel: Label = null;
    @property(Node)
    bg: Node = null;

    maxward: number = 0;
    realward: number = 0;
    lessward: number = 0;

    start() {

    }

    update(deltaTime: number) {

    }

    init() {
        // console.log("幸运弹窗奖励", config);
        AudioManager.ins.playOneShot(Url.AUDIO.SFX5, 1);

        this.maxward = this.pageConfig.cashMax;
        this.realward = this.pageConfig.cashVideoActual;
        this.lessward = this.pageConfig.cashCommonActual;
        this.jelly_enter(this.node);
        this.renderLocalUI();

        this.scheduleOnce(() => {
            this.getWard();
        }, 0.5)

    }

    async getWard() {
        ClientAPI.Point(NCPoint.REAPLUCKY, { userid: GlobalData.userId });
        AudioManager.ins.playOneShot(Url.AUDIO.SFX4, 1);
        let isforcePopAd = MainGameLogic.ins.getNextIntervalValue();
        let cash_get_type = 3;
        if (isforcePopAd) {
            let ad_state: Parameters<typeof ClientAPI.AD>[0];
            if (GlobalData.fullscTimes < 5) {
                ad_state = "full-screen"
            } else {
                ad_state = "incentive"
            }
            // 广告请求是否成功
            let isCom = await ClientAPI.AD(ad_state, 'ad');
            if (isCom) {
                cash_get_type = 2
                GlobalData.fullscTimes++;
                LocalStorageMgr.setItem(LocalStorageMgr.fullscTimes_key, GlobalData.fullscTimes);

                GlobalData.luckyWardNorgetTimes = 0;
                LocalStorageMgr.setItem(LocalStorageMgr.luckyWardNorgetTimes_key, GlobalData.luckyWardNorgetTimes);
            } else {
                GlobalData.luckyWardNorgetTimes++;
                LocalStorageMgr.setItem(LocalStorageMgr.luckyWardNorgetTimes_key, GlobalData.luckyWardNorgetTimes);
            }
            let cashAmount = cash_get_type == 2 ? this.realward : this.lessward;
            let config = await ServiceAPI.ForcePopReport(GlobalData.userId, cashAmount, cash_get_type);
            MainGameLogic.ins.updateCashLabel(config.cashTotal);
            MainGameLogic.ins.shwoGetCashEffect(v3(0, 0, 0));
            GlobalData.redPacket++;
            LocalStorageMgr.setItem(LocalStorageMgr.redPacket_key, GlobalData.redPacket);
        }
        await this.jelly_leave(this.node);
    }

    private __forcepop_report_cache__: ReturnType<typeof ServiceAPI.ForcePopReport>;
    async retryPassLevelReport(userId: number, cashAmount: number, type: number, retries: number = 3) {
        let attempt = 0;
        let config = null;
        while (attempt < retries) {
            try {
                config = await ServiceAPI.ForcePopReport(userId, cashAmount, type);
                if (config && config.cashTotal !== undefined) {
                    this.__forcepop_report_cache__ = config;
                    return config;
                } else {
                    console.warn("ForcePopReport 返回空值或 cashTotal 未定义");
                }
            } catch (error) {
                console.error(`ForcePopReport 请求失败 (第 ${attempt + 1} 次):`, error);
            }
            attempt++;
            // 等待一段时间后重试
            await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟 1 秒
        }
        if (!this.__forcepop_report_cache__) {
            let con = {
                cashTotal: GlobalData.curCashTotal
            }
            return con
        }
        return this.__forcepop_report_cache__;
    }



    renderLocalUI() {
        this.maxWardLabel.string = MainGameLogic.ins.formatCashValue(this.lessward);
        this.lessWardLabel.node.active = true;
    }

    jelly_enter(node: Node, duration?: number) {
        let np = new mtec.NudityPromise<Node>();
        Tween.stopAllByTarget(node);
        duration = duration ?? 0.5;

        tween(node)
            .set({ scale: v3(0.8, 0.8, 1) })
            .to(duration, { scale: v3(1, 1, 1) }, { easing: 'elasticOut' })
            .set({ scale: v3(1, 1, 1) })
            .call(() => np.resolve(node))
            .start();

        return np.promise;
    }
    jelly_leave(node: Node, duration?: number) {
        Tween.stopAllByTarget(node);
        duration = duration ?? 0.25;

        tween(node)
            .delay(1)
            .to(duration, { scale: v3(0.8, 0.8, 1) }, { easing: "backIn" })
            .set({ scale: v3(0.8, 0.8, 1) })
            .call(() => {
                PoolManager.putObject('LuckywardPage', node)
            })
            .start();


    }
}

